<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css';
import { onBeforeUnmount, ref, shallowRef } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
const editorRef = shallowRef();
const model=defineModel();

// 内容 HTML
const valueHtml = ref('');
const toolbarConfig = {};

const editorConfig= { placeholder: '请输入内容...' ,MENU_CONF:{}};
let {apiBase,imgBase}=useRuntimeConfig().public;
const route=useRoute()
if(route.path.startsWith('/backend')){
  apiBase=apiBase+'/backend';
}
//@ts-ignore
editorConfig.MENU_CONF['uploadImage'] = {
  server: `${apiBase}/tools/uploadFile`,
  fieldName:'file',
  headers: { Authorization: useLoginStore().token },
  customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
    let { data:{file_path},code,message} = res;
    // res 即服务端的返回结果
    if(code !== 200) {
      ElMessage.error('上传失败', message)
      return
    }else{
      const url=`${imgBase}/${file_path}`;
      //@ts-ignore
      insertFn(url, '', url)
    }

  },
}
editorConfig.MENU_CONF['uploadVideo'] = {
  server: `${apiBase}/tools/uploadFile`,
  fieldName:'file',
  headers: { Authorization: useLoginStore().token },
  customInsert(res: any, insertFn: InsertFnType) {  // TS 语法
    let { data:{file_path},code,message} = res;
    // res 即服务端的返回结果
    if(code !== 200) {
      ElMessage.error('上传失败', message)
      return
    }else{
      const url=`${imgBase}/${file_path}`;
      //@ts-ignore
      insertFn(url, '')
    }

  },
}
// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;

  editor.destroy();
});

const handleCreated = (editor) => {
  console.log('created', editor);
  editorRef.value = editor; // 记录 editor 实例，重要！
};
const handleChange = (edit) => {
  if(edit.isEmpty()){
    model.value='';
  }else{
  //@ts-ignore
    model.value=edit.getHtml();
  }
};
watchEffect(()=>{
  if(model.value!==valueHtml.value){
    //@ts-ignore
    valueHtml.value=model.value;
  }
})
</script>

<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        style="border-bottom: 1px solid #ccc"
    />
    <Editor
        :defaultConfig="editorConfig"
        v-model="valueHtml"
        style="height: 400px; overflow-y: hidden"
        @onCreated="handleCreated"
        @onChange="handleChange"
    />
  </div>
</template>

<style scoped lang="scss">

</style>